<?php

namespace App\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Core\JWT;
use App\Models\User;

class AuthMiddleware
{
    public function handle(): void
    {
        $token = Request::bearerToken();
        
        if (!$token) {
            Response::error('未提供认证令牌', 401);
        }
        
        $payload = JWT::decode($token);
        
        if (!$payload) {
            Response::error('无效的认证令牌', 401);
        }
        
        // 验证用户是否存在
        $user = User::findById($payload->user_id);
        
        if (!$user) {
            Response::error('用户不存在', 401);
        }
        
        // 将用户信息存储到全局变量中
        $GLOBALS['current_user'] = $user;
    }
}

